<template lang="pug">
  v-form(direction="vertical" style="width:400px")
    v-form-item(label="选择系统" prop="region")
      v-select(v-model="formData.system_key" placeholder="请选择系统" notfound="无法找到" :data="systemlist" @change="selectSystem")
      v-input(type="hidden" placeholder="系统名称" size="large" v-model="formData.system_name")
    v-form-item(label="角色名称")
      v-input(type="text" placeholder="角色名称" size="large" v-model="formData.role_name")
    v-form-item(label="角色描述" required)
      v-input(type="textarea" placeholder="角色描述" size="large" v-model="formData.remark")
    v-form-item(style="margin-top:24px")
      v-button( type="primary" html-type="button" @click="submitForm") 确定
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  name: 'roles-create',
  data () {
    return {
      systemlist: [{value: '1', label: '区域1'}, {value: '2', label: '区域2'}],
      formData: {
        role_name: '',
        system_key: '',
        system_name: '',
        permissions: [],
        remark: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'systems'
    ])
  },
  mounted () {
    this.getSystems()
  },
  methods: {
    getSystems () {
      if (this.systems) {
        let systemlist = []
        this.systems.forEach(system => {
          systemlist.push({
            value: system.system_key,
            label: system.system_name
          })
        }, this)
        this.systemlist = systemlist
      } else {
        this.$http.get('rbac/system?pageSize=1000').then(res => {
          let data = res.data
          let systemlist = []
          data.result.forEach(system => {
            systemlist.push({
              value: system.system_key,
              label: system.system_name
            })
          }, this)
          this.$store.dispatch('setSystemData', data.result)
          this.systemlist = systemlist
        })
      }
    },
    selectSystem (data) {
      for (let item of this.systemlist) {
        if (item.value === data) {
          this.formData.system_name = item.label
        }
      }
    },
    submitForm () {
      this.$http.post('rbac/role', this.formData)
        .then(res => {
          let result = res.data
          if (result.ret === 0) {
            this.$message.info(result.msg)
            this.formData = {
              name: '',
              domain: '',
              path: ''
            }
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>
